package com.quectel.cms.controller.partybuilding;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.partybuilding.PartyPersonOrganizationChangeVo;
import com.quectel.constant.core.partybuilding.PartyBuildingConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

import static cn.hutool.core.text.CharSequenceUtil.splitTrim;
import static com.quectel.constant.global.SystemConstants.STATUSES;

/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:17
 */
@RestController
@RequestMapping("partyPerson")
@Tag(name = "PartyPersonController", description = "党员管理相关api")
public class PartyPersonController extends BaseController {

    @DubboReference
    private PartyPersonService partyPersonService;
    @DubboReference
    private PartyOrganizationService partyOrganizationService;


    /**
     * 列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "partyPerson:exportExcel")
    @Operation(summary = "导出党员信息")
    @Log(express = "导出党员信息")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<PartyPersonDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<PartyPersonDto> list = partyPersonService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属党组织", "姓名", "性别", "手机号", "生日","党籍状态", "流动党员","失联状态",};
        List<String[]> dataList = new ArrayList<>();
        for (PartyPersonDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getParty() == null ? "" : data.getParty().getName();
            item[1] = data.getName();
            item[2] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.GENDER, data.getGender() + "");
            item[3] = data.getMobile();
            item[4] = DateUtils.format(data.getBirthDate(), DateUtils.FormatType.SIMPLE);
            item[5] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.PARTY_MEMBERSHIP_STATUS, data.getPartyMembershipStatus() + "");
            item[6] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.YES_OR_NOT, data.getFlowStatus() + "");
            item[7] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.YES_OR_NOT, data.getMissingStatus() + "");
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "党员信息", headers, dataList, "党员信息");

    }

    @PostMapping("importExcel")
    @RequirePermissions(values = "partyPerson:importExcel")
    @Operation(summary = "党员数据导入")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {
        final Long tenantId = SessionHolder.getSysUser().getTenantId();
        Date currentDate = new Date();
        int totalCount = 0;
        int successCount = 0;

        String sysUserName = SessionHolder.getSysUser().getUsername();
        List<PartyPersonDto> partyPersonDtos = new ArrayList<>();
        Iterator<String> fileNames = request.getFileNames();

        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    //校验楼栋数据合法性
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    for (Map<Integer, String> map : analysis) {
                        try {
                            PartyOrganizationDto organizationDto = partyOrganizationService.selectByName(tenantId, map.get(0));
                            if (organizationDto == null) {
                                continue;
                            }

                            PartyPersonDto dto = new PartyPersonDto();
                            dto.setTenantId(tenantId);
                            dto.setPartyId(organizationDto.getId());
                            dto.setName(map.get(1));
                            dto.setGender(Objects.equals("男", map.get(2)) ? SystemConstants.MALE : SystemConstants.FEMALE);
                            dto.setMobile(map.get(3));
                            dto.setPartyMembershipStatus(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.PARTY_MEMBERSHIP_STATUS, map.get(4), Byte.class));
                            dto.setFlowStatus(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.YES_OR_NOT, map.get(5), Byte.class));
                            dto.setMissingStatus(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.YES_OR_NOT, map.get(6), Byte.class));
                            dto.setCreator(sysUserName);
                            dto.setCreateTime(currentDate);
                            partyPersonDtos.add(dto);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                } catch (Exception e) {
                    logger.error("解析信息出错");
                }
            }
        }
        for (PartyPersonDto dto : partyPersonDtos) {
            try {
                successCount++;
                PartyPersonDto dbValue = partyPersonService.selectOne(dto.getTenantId(),dto.getMobile());
                if (dbValue != null) {
                    continue;
                }
                partyPersonService.save(dto);
            } catch (Exception e) {
                logger.error("导入失败", e);
                continue;
            }
        }
        return Response.error("导入成功,导入成功数量为:" + successCount);
    }


    @PostMapping("changeOrganization")
    @Operation(summary = "变更党员所属党组织")
    public Response<Object> changeOrganization(
            @RequestBody PartyPersonOrganizationChangeVo changeVo
    ) {

        PartyOrganizationDto organizationDto = partyOrganizationService.selectById(changeVo.getPartyOrganizationId());

        if (organizationDto!=null
        && !organizationDto.getParentId().equals(SystemConstants.TREE_DEFAULT_PARENT_ID)){
            for (PartyPersonDto partyPerson : changeVo.getPartyPersons()) {
                PartyPersonDto updately = new PartyPersonDto();
                updately.setId(partyPerson.getId());
                updately.setPartyId(changeVo.getPartyOrganizationId());
                partyPersonService.updateById(updately);
            }
        }else {
            return Response.error("党员不允许变更到根党组织");
        }
        return Response.ok();
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "partyPerson:list")
    @Operation(summary = "分页获取党员管理列表")
    public Response<Page<PartyPersonDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        Long partyId = request.getLong("partyId");
        if (partyId != null){
            List<PartyOrganizationDto> recursion = partyOrganizationService.recursion(partyId);

            request.getParams().put(PartyBuildingConstants.PARTY_ID_COLLECTION_FLAG, recursion.stream().map(PartyOrganizationDto::getId).toArray(Long[]::new));
        }

        String personTypeArr = request.getString(SystemConstants.STATUSES);
        request.getParams().put(STATUSES, splitTrim(personTypeArr, ","));

        int total = partyPersonService.queryTotal(request.getParams());

        List<PartyPersonDto> list = null;
        if (total > 0) {
            list = partyPersonService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<PartyPersonDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PartyPersonDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "partyPerson:edit")
    @Operation(summary = "在编辑时根据id查询党员管理详情")
    public Response<PartyPersonDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partyPersonService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyPersonDto partyPersonDto = partyPersonService.selectById(id);

        return Response.<PartyPersonDto>ok().wrap(partyPersonDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "partyPerson:info")
    @Operation(summary = "根据id查询党员管理的详情")
    public Response<PartyPersonDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (partyPersonService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyPersonDto partyPersonDto = partyPersonService.selectById(id);

        return Response.<PartyPersonDto>ok().wrap(partyPersonDto);
    }

    /**
     * 保存
     *
     * @param partyPersonDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "partyPerson:edit")
    @Operation(summary = "新增党员管理")
    public Response<Object> save(@RequestBody @Validated PartyPersonDto partyPersonDto) {

        PartyPersonDto dbValue =
                partyPersonService.selectOne(Objects.requireNonNull(SessionHolder.getSysUser()).getTenantId(), partyPersonDto.getMobile());
        if (dbValue != null) {
            return Response.error("当前租户下已存在该手机号，不允许重复添加");
        }

        Long partyId = partyPersonDto.getPartyId();
        //填充基础数据
        fillSaveCommonData(partyPersonDto);

        partyPersonDto.setPartyId(partyId);
        partyPersonService.save(partyPersonDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param partyPersonDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "partyPerson:edit")
    @Operation(summary = "根据id修改党员管理")
    public Response<Object> update(@RequestBody  @Validated PartyPersonDto partyPersonDto) {

        PartyPersonDto dbValue =
                partyPersonService.selectOne(Objects.requireNonNull(SessionHolder.getSysUser()).getTenantId(), partyPersonDto.getMobile());
        if (dbValue != null && !Objects.equals(dbValue.getId(), partyPersonDto.getId())) {
            return Response.error("当前租户下已存在该手机号，不允许重复添加");
        }

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(partyPersonDto.getId()));
        if (partyPersonService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(partyPersonDto);

        partyPersonService.updateById(partyPersonDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "partyPerson:delete")
    @Operation(summary = "根据多条记录id批量删除党员管理")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (partyPersonService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        partyPersonService.deleteBatch(ids);

        return Response.ok();
    }
}
